package cn.eweb.ttkt;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.baidu.mapapi.*;
import com.baidu.mapapi.MapView.LayoutParams;


public class MyMapActivity extends MapActivity {
	
	static View mPopView = null;	// 点击mark时弹出的气泡View
	static MapView mMapView = null;
	static TextView mText = null;
	int iZoom = 0;
	OverItemT overitem = null;
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        
		TtktApp app = (TtktApp)this.getApplication();
		if (app.mBMapMan == null) {
			app.mBMapMan = new BMapManager(getApplication());
			app.mBMapMan.init(app.mStrKey, new TtktApp.MyGeneralListener());
		}
		app.mBMapMan.start();
        // 如果使用地图SDK，请初始化地图Activity
        super.initMapActivity(app.mBMapMan);
        
        mMapView = (MapView)findViewById(R.id.bmapView);
        mMapView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mMapView.setBuiltInZoomControls(true);
        
        //设置在缩放动画过程中也显示overlay,默认为不绘制
        mMapView.setDrawOverlayWhenZooming(true);
        GeoPoint point =new GeoPoint((int)(31.653584*1e6), (int)(120.7525*1e6));
        mMapView.getController().setCenter(point);
  
        // 添加ItemizedOverlay
		Drawable marker = getResources().getDrawable(R.drawable.icon_marka);  //得到需要标在地图上的资源
		marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());   //为maker定义位置和边界
		
		overitem = new OverItemT(marker, this);
		mMapView.getOverlays().add(overitem); //添加ItemizedOverlay实例到mMapView
		
		// 创建点击mark时的弹出泡泡
		mPopView=super.getLayoutInflater().inflate(R.layout.popview, null);
		mText = (TextView)mPopView.findViewById(R.id.pop);
		mMapView.addView( mPopView,
                new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                		null, MapView.LayoutParams.TOP_LEFT));
		mPopView.setVisibility(View.GONE);
		iZoom = mMapView.getZoomLevel();
	}

	@Override
	protected void onPause() {
		TtktApp app = (TtktApp)this.getApplication();
		if(app.mBMapMan != null)
			app.mBMapMan.stop();
		super.onPause();
	}
	@Override
	protected void onResume() {
		TtktApp app = (TtktApp)this.getApplication();
		app.mBMapMan.start();
		super.onResume();
//		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { 
			AlertDialog.Builder ad = new AlertDialog.Builder(this);
        	ad.setIcon(android.R.drawable.ic_dialog_info);
    		ad.setTitle(getString(R.string.quit)); // 设置标题 
            ad.setMessage(getString(R.string.quit_confirm));
            ad.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {

    			public void onClick(DialogInterface dialog, int which) {
    				dialog.cancel();
    				MyMapActivity.this.finish();
    			} 
            });  
            ad.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {

    			public void onClick(DialogInterface dialog, int which) {
    				dialog.cancel();
    			}
                   
            });  
            AlertDialog alert = ad.create();
            alert.show();
        }
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		/*
         * 
         * add()方法的四个参数，依次是：
         * 1、组别，如果不分组的话就写Menu.NONE,
         * 2、Id，这个很重要，Android根据这个Id来确定不同的菜单
         * 3、顺序，那个菜单现在在前面由这个参数的大小决定
         * 4、文本，菜单的显示文本
         */
        menu.add(Menu.NONE, Menu.FIRST + 1, 1, getString(R.string.quit)).setIcon(
        		android.R.drawable.ic_menu_revert);
        return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
        case Menu.FIRST + 1:
        	MyMapActivity.this.finish();
            break;
		}
		return false;
	}
}
class OverItemT extends ItemizedOverlay<OverlayItem> {

	public List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();
	private Context mContext;

	private double mLat1 = 31.6048; // point1纬度
	private double mLon1 = 120.78947; // point1经度
	
	private double mLat2 = 31.65137;
	private double mLon2 = 120.75397;
	
	private double mLat3 = 31.664255;
	private double mLon3 = 120.7701;

	public OverItemT(Drawable marker, Context context) {
		super(boundCenterBottom(marker));
		
		this.mContext = context;

		// 用给定的经纬度构造GeoPoint，单位是微度 (度 * 1E6)
		GeoPoint p1 = new GeoPoint((int) (mLat1 * 1E6), (int) (mLon1 * 1E6));
		GeoPoint p2 = new GeoPoint((int) (mLat2 * 1E6), (int) (mLon2 * 1E6));
		GeoPoint p3 = new GeoPoint((int) (mLat3 * 1E6), (int) (mLon3 * 1E6));
		
		OverlayItem oi1 = new OverlayItem(p1, mContext.getString(R.string.p1_title), mContext.getString(R.string.p1_snippet));
		OverlayItem oi2 = new OverlayItem(p2, mContext.getString(R.string.p2_title), mContext.getString(R.string.p2_snippet));
		OverlayItem oi3 = new OverlayItem(p3, mContext.getString(R.string.p3_title), mContext.getString(R.string.p3_snippet));
		
		Drawable marker1 = mContext.getResources().getDrawable(R.drawable.icon_marka);  //得到需要标在地图上的资源
		marker1.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());   //为maker定义位置和边界
		Drawable marker2 = mContext.getResources().getDrawable(R.drawable.icon_markb);  //得到需要标在地图上的资源
		marker1.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());   //为maker定义位置和边界
		Drawable marker3 = mContext.getResources().getDrawable(R.drawable.icon_markc);  //得到需要标在地图上的资源
		marker1.setBounds(0, 0, marker.getIntrinsicWidth(), marker
				.getIntrinsicHeight());   //为maker定义位置和边界
		
		oi1.setMarker(marker1);
		oi2.setMarker(marker2);
		oi3.setMarker(marker3);
		
		// 构造OverlayItem的三个参数依次为：item的位置，标题文本，文字片段
		mGeoList.add(oi1);
		mGeoList.add(oi2);
		mGeoList.add(oi3);
		populate();  //createItem(int)方法构造item。一旦有了数据，在调用其它方法前，首先调用这个方法
	}

	public void updateOverlay()
	{
		populate();
	}

	@Override
	public void draw(Canvas canvas, MapView mapView, boolean shadow) {

		// Projection接口用于屏幕像素坐标和经纬度坐标之间的变换
		Projection projection = mapView.getProjection(); 
		for (int index = size() - 1; index >= 0; index--) { // 遍历mGeoList
			OverlayItem overLayItem = getItem(index); // 得到给定索引的item

			String title = overLayItem.getTitle();
			// 把经纬度变换到相对于MapView左上角的屏幕像素坐标
			Point point = projection.toPixels(overLayItem.getPoint(), null); 

			// 可在此处添加您的绘制代码
			Paint paintText = new Paint();
			Typeface font = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
			paintText.setTypeface(font);
			paintText.setColor(Color.BLUE);
			paintText.setTextSize(20);
			canvas.drawText(title, point.x-30, point.y, paintText); // 绘制文本
			//调整一个drawable边界，使得（0，0）是这个drawable底部最后一行中心的一个像素
			boundCenterBottom(overLayItem.getMarker(0));
		}

		super.draw(canvas, mapView, shadow);
		
	}

	@Override
	protected OverlayItem createItem(int i) {
		// TODO Auto-generated method stub
		return mGeoList.get(i);
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return mGeoList.size();
	}
	@Override
	// 处理当点击事件
	protected boolean onTap(int i) {
		setFocus(mGeoList.get(i));
		// 更新气泡位置,并使之显示
		GeoPoint pt = mGeoList.get(i).getPoint();
		MyMapActivity.mText.setText(mGeoList.get(i).getSnippet());
		MyMapActivity.mMapView.updateViewLayout( MyMapActivity.mPopView,
                new MapView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                		pt, MapView.LayoutParams.BOTTOM_CENTER));
		MyMapActivity.mPopView.setVisibility(View.VISIBLE);
//		Toast.makeText(this.mContext, mGeoList.get(i).getSnippet(),
//				Toast.LENGTH_SHORT).show();
		return true;
	}

	@Override
	public boolean onTap(GeoPoint arg0, MapView arg1) {
		// 消去弹出的气泡
		MyMapActivity.mPopView.setVisibility(View.GONE);
		return super.onTap(arg0, arg1);
	}
}
